package com.yyfax.pay.order.data.service.impl;


import javax.annotation.Resource;

import com.yyfax.pay.third.facade.fuiou.ProtocolAdaptService;
import com.yyfax.pay.third.facade.fuiou.ProtocolService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import com.fuiou.mpay.encrypt.DESCoderFUIOU;
import com.fuiou.util.MD5;
import com.google.common.collect.Maps;
import com.yyfax.framework.common.Log;
import com.yyfax.framework.common.OpResponse;
import com.yyfax.framework.yyfax.enums.YesNoEnum;
import com.yyfax.pay.common.enums.*;
import com.yyfax.pay.common.exception.PayException;
import com.yyfax.pay.common.exception.PayExceptionCode;
import com.yyfax.pay.common.util.FuiouIdUtils;
import com.yyfax.pay.order.data.dao.UserPaymentDao;
import com.yyfax.pay.order.data.dao.protocol.ProtocolUntieOrderDao;
import com.yyfax.pay.order.data.service.ProtocolUntieService;
import com.yyfax.pay.order.data.service.UserPaymentService;
import com.yyfax.pay.order.model.domain.ProtocolUntieOrderDO;
import com.yyfax.pay.order.model.po.UserPaymentPO;
import com.yyfax.pay.vo.order.ProtocolPayUnBindReq;

@Service
public class ProtocolUntieServiceImpl implements ProtocolUntieService {

	@Resource
	private ProtocolUntieOrderDao protocolUntieOrderDao;

	@Resource
	private FuiouIdUtils fuiouIdUtils;

	@Resource
	private UserPaymentService userPaymentService;

	@Resource
	private UserPaymentDao userPaymentDao;

	@Resource
	private ProtocolAdaptService protocolAdaptService;

	protected Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 协议解绑
	 * 
	 * @author wangjwy
	 * @date 2018/6/19 9:51
	 * @since 2.2.0
	 * @param params, merchantCode
	 * @return com.yyfax.framework.common.OpResponse
	 */
	@Override
	public OpResponse unBind(ProtocolPayUnBindReq params, String merchantCode) {
		final String OP = "ProtocolUntieServiceImpl.unBind";

		// 查询支付扩展信息
		UserPaymentPO userPaymentPO = userPaymentService.query(merchantCode, params.getUserId(), PaymentEnum.FUIOU_PROTOCOL_PAY.getValue());
		if (userPaymentPO == null || StringUtils.isBlank(userPaymentPO.getProtocolCode()) || YesNoEnum.NO.isValue(userPaymentPO.getState())) {
			// 查到存在协议号,直接返回
			logger.info(Log.op(OP).msg("查到用户没有绑卡相关信息,直接返回").kv("orderId", params.getOrderId()).kv("paymentCode", params.getPaymentCode())
					.kv("merchantCode", merchantCode).kv("userId", params.getUserId()).toString());
			throw PayExceptionCode.ERROR_USER_PAYMENT_NOT_EXISTS.exp();
		}
		// 持久化订单
		ProtocolUntieOrderDO untieOrderDO = buildUnbindOrder(params, merchantCode, userPaymentPO);
		try {
			protocolUntieOrderDao.insert(untieOrderDO);
		} catch (DuplicateKeyException e) {
			ProtocolUntieOrderDO exist = protocolUntieOrderDao.selectByMerchantCodeAndUserId(untieOrderDO.getMerchantCode(),
					untieOrderDO.getUserId());
			if (null == exist) {
				logger.error(Log.op(OP).msg("保存解绑订单主键冲突").kv("orderid", params.getOrderId()).toString());
				throw PayExceptionCode.SYS_ERROR.exp();
			}
			untieOrderDO = exist;
			// 订单状态为成功直接返回
			if (OrderStateEnum.SUCCESS.isValue(String.valueOf(untieOrderDO.getState()))) {
				logger.info(
						Log.op(OP).msg("订单已经出结果,直接返回").kv("busi_id", untieOrderDO.getBusiId()).kv("orderId", untieOrderDO.getOrderId()).toString());
				return OpResponse.success();
			}
			if (OrderStateEnum.FAIL.isValue(String.valueOf(untieOrderDO.getState()))) {
				logger.warn(Log.op(OP).msg("查询到订单结果为失败,直接返回").kv("busi_id", untieOrderDO.getBusiId()).kv("orderId", untieOrderDO.getOrderId())
						.toString());
				throw new PayException(untieOrderDO.getRespCode(), untieOrderDO.getRespDesc());
			}
		}

		int uCount = protocolUntieOrderDao.updateState(untieOrderDO.getBusiId(), Integer.valueOf(OrderStateEnum.DEALING.getValue()),
				Integer.valueOf(OrderStateEnum.INI.getValue()));
		if (1 != uCount) {
			logger.warn(Log.op(OP).msg("修改订单状态未命中,不处理").toString());
			OpResponse response = new OpResponse();
			response.setCode(PayExceptionCode.PROCESSING.getCode());
			response.setDisplay(PayExceptionCode.PROCESSING.getDesc());
			return response;
		}

		ProtocolService adaptiveTradeService = protocolAdaptService.getAdaptiveTradeService(ProtocolEnum.form(params.getPaymentCode()));
		return adaptiveTradeService.untieProtocol(untieOrderDO, userPaymentPO);
	}


	// private void saveQueryTask(ProtocolUntieOrderDO po) {
	// final String OP = "ProtocolUntieServiceImpl.saveQueryTask";
	//
	// try {
	// fuiouDepositCommonService.saveQueryTask(po.getMerchantCode(),po.getBusiId(),FuiouBusiTypeEnum.PROTOCOL_UNBIND);
	// }catch (Exception e) {
	// logger.error("生成绑卡超时查询任务异常，busiId:" + po.getBusiId(), e.toString());
	// }
	// }


	/**
	 * 构建实体
	 * 
	 * @author wangjwy
	 * @date 2018/6/9 17:20
	 * @since 2.2.0
	 * @param params, merchantCode
	 * @return com.yyfax.pay.order.model.domain.ProtocolUntieOrderDO
	 * @throws Exception
	 */
	private ProtocolUntieOrderDO buildUnbindOrder(ProtocolPayUnBindReq params, String merchantCode, UserPaymentPO userPaymentPO) {
		final String OP = "ProtocolUntieServiceImpl.buildUnbindOrder";
		ProtocolUntieOrderDO untieOrderDO = new ProtocolUntieOrderDO();
		untieOrderDO.setBusiId(fuiouIdUtils.generateBusiId(FuiouBusiTypeEnum.PROTOCOL_UNBIND, merchantCode));
		untieOrderDO.setMerchantCode(merchantCode);
		untieOrderDO.setOrderId(params.getOrderId());
		untieOrderDO.setOrderTime(params.getOrderTime());
		untieOrderDO.setUserAuthId(userPaymentPO.getUserAuthId());
		untieOrderDO.setProtocolCode(userPaymentPO.getProtocolCode());
		untieOrderDO.setState(Integer.valueOf(OrderStateEnum.INI.getValue()));
		untieOrderDO.setUserId(params.getUserId());
		return untieOrderDO;
	}
}
